package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.Customer;
import com.deliveryservicesystem.model.Subscription;
import com.deliveryservicesystem.service.crud.CustomerCrudService;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: CustomerCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class CustomerCrudServiceImpl implements CustomerCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public CustomerCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Customer customer) throws PreexistingEntityException, Exception
    {
        if (customer.getSubscriptionList() == null)
        {
            customer.setSubscriptionList(new ArrayList<Subscription>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Subscription> attachedSubscriptionList = new ArrayList<>();
            for (Subscription subscriptionListSubscriptionToAttach : customer.getSubscriptionList())
            {
                subscriptionListSubscriptionToAttach = em.getReference(subscriptionListSubscriptionToAttach.getClass(), subscriptionListSubscriptionToAttach.getSubscriptionNo());
                attachedSubscriptionList.add(subscriptionListSubscriptionToAttach);
            }
            customer.setSubscriptionList(attachedSubscriptionList);
            em.persist(customer);
            for (Subscription subscriptionListSubscription : customer.getSubscriptionList())
            {
                Customer oldCustomerNoOfSubscriptionListSubscription = subscriptionListSubscription.getCustomerNo();
                subscriptionListSubscription.setCustomerNo(customer);
                subscriptionListSubscription = em.merge(subscriptionListSubscription);
                if (oldCustomerNoOfSubscriptionListSubscription != null)
                {
                    oldCustomerNoOfSubscriptionListSubscription.getSubscriptionList().remove(subscriptionListSubscription);
                    oldCustomerNoOfSubscriptionListSubscription = em.merge(oldCustomerNoOfSubscriptionListSubscription);
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(customer.getCustomerNo()) != null)
            {
                throw new PreexistingEntityException("Customer " + customer + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Customer customer) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Customer persistentCustomer = em.find(Customer.class, customer.getCustomerNo());
            List<Subscription> subscriptionListOld = persistentCustomer.getSubscriptionList();
            List<Subscription> subscriptionListNew = customer.getSubscriptionList();
            List<Subscription> attachedSubscriptionListNew = new ArrayList<>();
            for (Subscription subscriptionListNewSubscriptionToAttach : subscriptionListNew)
            {
                subscriptionListNewSubscriptionToAttach = em.getReference(subscriptionListNewSubscriptionToAttach.getClass(), subscriptionListNewSubscriptionToAttach.getSubscriptionNo());
                attachedSubscriptionListNew.add(subscriptionListNewSubscriptionToAttach);
            }
            subscriptionListNew = attachedSubscriptionListNew;
            customer.setSubscriptionList(subscriptionListNew);
            customer = em.merge(customer);
            for (Subscription subscriptionListOldSubscription : subscriptionListOld)
            {
                if (!subscriptionListNew.contains(subscriptionListOldSubscription))
                {
                    subscriptionListOldSubscription.setCustomerNo(null);
                    subscriptionListOldSubscription = em.merge(subscriptionListOldSubscription);
                }
            }
            for (Subscription subscriptionListNewSubscription : subscriptionListNew)
            {
                if (!subscriptionListOld.contains(subscriptionListNewSubscription))
                {
                    Customer oldCustomerNoOfSubscriptionListNewSubscription = subscriptionListNewSubscription.getCustomerNo();
                    subscriptionListNewSubscription.setCustomerNo(customer);
                    subscriptionListNewSubscription = em.merge(subscriptionListNewSubscription);
                    if (oldCustomerNoOfSubscriptionListNewSubscription != null && !oldCustomerNoOfSubscriptionListNewSubscription.equals(customer))
                    {
                        oldCustomerNoOfSubscriptionListNewSubscription.getSubscriptionList().remove(subscriptionListNewSubscription);
                        oldCustomerNoOfSubscriptionListNewSubscription = em.merge(oldCustomerNoOfSubscriptionListNewSubscription);
                    }
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = customer.getCustomerNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The customer with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Customer customer;
            try
            {
                customer = em.getReference(Customer.class, id);
                customer.getCustomerNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The customer with id " + id + " no longer exists.", enfe);
            }
            List<Subscription> subscriptionList = customer.getSubscriptionList();
            for (Subscription subscriptionListSubscription : subscriptionList)
            {
                subscriptionListSubscription.setCustomerNo(null);
                subscriptionListSubscription = em.merge(subscriptionListSubscription);
            }
            em.remove(customer);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Customer> findEntities()
    {
        return findCustomerEntities(true, -1, -1);
    }

    @Override
    public List<Customer> findEntities(int maxResults, int firstResult)
    {
        return findCustomerEntities(false, maxResults, firstResult);
    }

    private List<Customer> findCustomerEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Customer.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Customer findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Customer.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Customer> rt = cq.from(Customer.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
